<template>
  <div>
    <div class="confirmInfo_list_wrap">
      <ul class="confirmInfo_list">
        <li v-for="(item, index) in confirmInfo" :key="index" class="confirmInfo_item" :class="index === activeConfirmInfo ? 'active' : ''" @click="chooseConfirmInfo(item, index)">
          <div class="confirmInfo_item_filling gl_clear">
            <!-- 个人/团体头像 -->
            <div class="confirmInfo_img_wrap gl_fl">
              <van-image :src="imagePre + item.imagePath" fit="contain" radius="10" width="108px" height="108px">
                <template v-slot:error>
                  <van-image width="108px" height="108px" fit="contain" :src="defaultPhoto" />
                </template>
              </van-image>
            </div>
            <!-- 显示的基本信息 -->
            <div class="confirmInfo_info">
              <div class="confirmInfo_info_title gl_ellipsis">
                <span v-if="item.name">{{ item.name }}</span>
                <span v-else class="no_info_gray">请完善信息</span>
              </div>
              <template v-if="currentUserType === 'Personal'">
                <div class="confirmInfo_info_type">{{ idCardTypeMap[item.idCardTypeCode] ? idCardTypeMap[item.idCardTypeCode].value : '' }}</div>
                <div class="confirmInfo_info_type">{{ item.idCardNumber }}</div>
              </template>
              <template v-else>
                <div class="confirmInfo_info_desc gl_ellipsis">{{ item.contactPerson }}</div>
                <div class="confirmInfo_info_desc gl_ellipsis">{{ item.phoneNumber }}</div>
                <!-- <div class="confirmInfo_info_desc gl_ellipsis">{{ addressDataForCheck(item.provinceCode, item.cityCode, item.countyCode) }}</div> -->
              </template>
            </div>
          </div>
        </li>
        <li v-if="confirmInfo.length" class="confirmInfo_item_edit" @click="clickEdit()">
          编辑{{ currentUserType === 'Personal' ? '个人' : '团体' }}信息
        </li>
        <li v-if="!confirmInfo.length" class="noConfirmInfo">
          您信息缺失，请完善信息。
        </li>
      </ul>
    </div>

    <!-- 步骤按钮 -->
    <van-row gutter="10" class="bottom_btn_position">
      <van-col span="12" align="center">
        <van-button v-if="userType.userType.code === 'PersonalDelegation'" type="default" block @click="clickPrevStep()">上一步</van-button>
        <van-button v-else type="default" block @click="goback()">返回</van-button>
      </van-col>
      <van-col span="12" align="center">
        <van-button :disabled="!confirmInfo.length" :loading="nextLoading" type="info" block @click="clickNextStep()">下一步</van-button>
      </van-col>
    </van-row>

    <!-- 个人编辑弹框 -->
    <van-popup v-model="dialogVisibleForPersonal" get-container="#app" position="right" :style="{ width: '100%', height: '100%' }">
      <div class="add_member">
        <van-nav-bar class="main_header" title="编辑">
          <template #left>
            <span @click="dialogVisibleForPersonal = false">返回</span>
          </template>
          <template #right>
            <span @click="submitPersonalInfo">确定</span>
          </template>
        </van-nav-bar>
        <div class="add_member_content">
          <personal-info ref="refPersonalInfo" :user-data="createRegisterInput" :is-default-check="createRegisterInput.isApproved" />
        </div>
      </div>
    </van-popup>

    <!-- 团体编辑弹框 -->
    <van-popup v-model="dialogVisibleForTeam" get-container="#app" position="right" :style="{ width: '100%', height: '100%' }">
      <div class="add_member">
        <van-nav-bar class="main_header" title="编辑">
          <template #left>
            <span @click="dialogVisibleForTeam = false">返回</span>
          </template>
          <template #right>
            <span @click="submitTeamInfo">确定</span>
          </template>
        </van-nav-bar>
        <div class="add_member_content">
          <delegation-info ref="refDelegationInfo" :team-data="createDelegationInput" :is-default-check="createDelegationInput.isApproved" :organization-units-types="dict.delegationType" />
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { CopyData } from '@/lib';

import {
  api_POST_EventsManagementRegister,
  api_PUT_EventsManagementRegisterId,
  api_POST_EventsManagementDelegation, // 新建机构
  api_PUT_EventsManagementDelegationId,
  api_POST_EventsManagementEntryOrderAllowEntry // 确认是否有未支付的订单
} from '@/extend/api/gameswaggerApi/app';

import {
  SiSTKWEventsManagementCreateRegisterInput,
  SiSTKWEventsManagementCreateDelegationInput
} from '@/lib/form/game/swaggerForm';

import defaultPhoto from '@/assets/images/face_default.png';

import personalInfo from '@/viewMobile/components/PersonalInfo';
import delegationInfo from '@/viewMobile/components/DelegationInfo';

export default {
  components: {
    personalInfo,
    delegationInfo
  },
  props: {
    // 当前用户角色 Personal : 个人，Delegation：团体， PersonalDelegation：个人 + 团体
    userType: {
      type: Object,
      default () {
        return {};
      }
    },
    // 通过点击个人或团体传进来的状态
    currentUserType: {
      type: String,
      default: ''
    },
    requiredIdData: {
      type: Object,
      default () {
        return {};
      }
    },
    isShow: {
      type: Boolean
    },
    // 当前用户信息
    userInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    // 当前用户团体信息
    userTeamInfo: {
      type: Object,
      default () {
        return {};
      }
    },
    // 字典信息
    dict: {
      type: Object,
      default () {
        return {};
      }
    },
    // 字典信息
    district: {
      type: Array,
      default () {
        return [];
      }
    }
  },
  data () {
    return {
      activeConfirmInfo: 0, // 当前选中项，如果是多选，不选状态为 -1
      defaultPhoto: defaultPhoto, // 默认照片
      nextLoading: false, // 下一步按钮lodaing状态
      createRegisterInput: new SiSTKWEventsManagementCreateRegisterInput(),
      createDelegationInput: new SiSTKWEventsManagementCreateDelegationInput(),
      dialogVisibleForPersonal: false, // 控制个人信息弹窗显示
      dialogVisibleForTeam: false, // 控制团体信息弹窗显示
      confirmInfo: [], // 数据信息集合
      imagePre: WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + '/'
    };
  },
  computed: {
    ...mapState({
      cache: state => state.dict.cache
    }),
    idCardTypeMap() {
      const _map = {};
      this.dict.idCardType.forEach(item => {
        _map[item.code] = item;
      });
      return _map;
    }
  },
  watch: {
    dialogVisibleForPersonal(val) {
      if (!val) {
        this.createRegisterInput = new SiSTKWEventsManagementCreateRegisterInput();
      }
    },
    dialogVisibleForTeam(val) {
      if (!val) {
        this.createDelegationInput = new SiSTKWEventsManagementCreateDelegationInput();
      }
    },
    isShow: {
      immediate: true,
      deep: true,
      handler: function(val) {
        if (val) {
          this.getDictByType(['district']);
          if (this.currentUserType === 'Delegation') {
            this.confirmInfo = this.userTeamInfo ? [this.userTeamInfo] : [{}];
          } else {
            this.confirmInfo = this.userInfo ? [this.userInfo] : [{}];
          }
        }
      }
    },
    userInfo(val) {
      if (val) {
        this.confirmInfo = [this.userInfo];
      }
    },
    userTeamInfo(val) {
      if (val) {
        this.confirmInfo = [this.userTeamInfo];
      }
    }
  },
  methods: {
    // 若没有字典信息，外部可直接调用方法获取字典数据
    ...mapActions({ getDictByType: 'dict/getDictByType' }),
    // 编辑按钮
    clickEdit() {
      if (this.currentUserType === 'Delegation') {
        this.dialogVisibleForTeam = true;
        if (this.userTeamInfo) {
          CopyData(this.userTeamInfo, this.createDelegationInput);
        }
      } else {
        this.dialogVisibleForPersonal = true;
        if (this.userInfo) {
          CopyData(this.userInfo, this.createRegisterInput);
        }
      }
    },
    // 提交个人信息
    submitPersonalInfo() {
      this.$refs.refPersonalInfo.getInsideUserData()
        .then(
          res => {
            if (res.imagePath) {
              const _registerId = this.requiredIdData.registerId;
              if (_registerId) {
                this.updatePersonalInfo(res);
              } else {
                this.createPersonalInfo(res);
              }
            } else {
              this.$toast({ type: 'fail', message: `请上传头像` });
            }
          }
        );
    },
    // 更新个人信息
    updatePersonalInfo(res) {
      CopyData(res, this.createRegisterInput);
      this.personalInfoLoading = true;
      this.createRegisterInput.isCurrentUser = true;
      this.createRegisterInput.joinCurrentDelegation = false;
      api_PUT_EventsManagementRegisterId(this.requiredIdData.registerId, this.createRegisterInput)
        .then(
          () => {
            this.personalInfoLoading = false;
            this.dialogVisibleForPersonal = false;
            this.$toast({ type: 'success', message: `操作成功` });
            this.$emit('onGetUserInfo');
          },
          error => {
            this.personalInfoLoading = false;
            this.$toast({ type: 'fail', message: `修改用户信息失败 ${error.error.message}` });
          }
        );
    },
    // 创建个人信息
    createPersonalInfo(res) {
      CopyData(res, this.createRegisterInput);
      this.personalInfoLoading = true;
      this.createRegisterInput.isCurrentUser = true;
      this.createRegisterInput.joinCurrentDelegation = false;
      this.createRegisterInput.registerTypeCode = 'I';

      // 将空字符串转为Null
      for (const k in this.createRegisterInput) {
        const ktem = this.createRegisterInput[k];
        if (ktem === '') {
          this.createRegisterInput[k] = null;
        }
      }

      api_POST_EventsManagementRegister(this.createRegisterInput)
        .then(
          () => {
            this.personalInfoLoading = false;
            this.dialogVisibleForPersonal = false;
            this.$toast({ type: 'success', message: `操作成功` });
            this.$emit('reGetUserType');
          },
          error => {
            this.personalInfoLoading = false;
            this.$toast({ type: 'fail', message: `修改用户信息失败 ${error.error.message}` });
          }
        );
    },
    // 提交团体信息
    submitTeamInfo() {
      this.$refs.refDelegationInfo.getcreateDelegationInputVO()
        .then(
          res => {
            if (res.imagePath) {
              const _delegationId = this.requiredIdData.delegationId;
              if (_delegationId) {
                this.updateDelegationInfo(res);
              } else {
                this.createDelegationInfo(res);
              }
            } else {
              this.$toast({ type: 'fail', message: `请上传团体标志` });
            }
          }
        )
        .catch(
          error => {
            console.log('updateDelegationInfo -> error', error);
          }
        );
    },
    // 更新团体信息
    updateDelegationInfo (data) {
      api_PUT_EventsManagementDelegationId(this.requiredIdData.delegationId, data)
        .then(
          res => {
            this.dialogVisibleForTeam = false;
            this.$toast({ type: 'success', message: `操作成功` });
            this.$emit('onGetUserTeamInfo');
          }
        )
        .catch(
          error => {
            this.$toast({ type: 'fail', message: `修改团体信息失败 ${error.error.message}` });
          }
        );
    },
    // 创建一个团体
    createDelegationInfo (data) {
      api_POST_EventsManagementDelegation(data)
        .then(
          res => {
            this.dialogVisibleForTeam = false;
            this.$toast({ type: 'success', message: `操作成功` });
            this.$emit('onGetUserTeamInfo');
            this.$emit('reGetUserType');
          }
        )
        .catch(
          error => {
            this.$toast({ type: 'fail', message: `创建团体信息失败${'，' + error.error.message || ''}` });
            console.log('updateDelegationInfo -> error', error);
          }
        );
    },
    // 选择机构
    chooseConfirmInfo (item, index) {
      this.activeConfirmInfo = index;
    },
    // 收费赛事需校验是否存在未支付的订单，如果存在则无法执行报名
    checkAllowEntry () {
      this.nextLoading = true;
      const _vo = {
        competitionId: this.gameInfo.id
      };
      if (this.currentUserType === 'Personal') {
        _vo.registerId = this.requiredIdData.registerId;
      }
      if (this.currentUserType === 'Delegation') {
        _vo.delegationId = this.requiredIdData.delegationId;
      }
      // _vo.delegationId.
      api_POST_EventsManagementEntryOrderAllowEntry(_vo)
        .then(
          res => {
            this.nextLoading = false;
            if (res.allowEntry) {
              this.$emit('onNextStep');
            } else {
              this.$toast({ type: 'fail', message: `无法继续报名 ${res.message}` });
            }
          }
        )
        .catch(
          error => {
            this.nextLoading = false;
            this.$toast({ type: 'fail', message: `校验信息获取失败！` });
            console.log(error);
          }
        );
    },
    // 点击执行上一步操作
    clickPrevStep () {
      this.$emit('onPrevStep');
    },
    // 点击执行下一步操作
    clickNextStep () {
      // activeConfirmInfo初始值为-1，当需要从多项中选择其一时用此方案
      const _isComplete = this.checkInfoComplete();
      if (_isComplete) {
        this.checkAllowEntry();
      } else {
        this.$toast({ type: 'fail', message: `请确认并补全您的基本信息` });
      }
    },
    // 校验信息是否完整
    checkInfoComplete() {
      let _infoComplete = false;
      if (this.currentUserType === 'Personal') {
        _infoComplete =
          Boolean(this.userInfo) &&
          Boolean(this.userInfo.name) &&
          Boolean(this.userInfo.birthDate) &&
          Boolean(this.userInfo.phoneNumber) &&
          Boolean(this.userInfo.idCardNumber);
      }
      if (this.currentUserType === 'Delegation') {
        _infoComplete =
          Boolean(this.userTeamInfo) &&
          Boolean(this.userTeamInfo.name) &&
          Boolean(this.userTeamInfo.provinceCode) &&
          Boolean(this.userTeamInfo.delegationTypeCode) &&
          Boolean(this.userTeamInfo.phoneNumber);
      }
      console.log('checkInfoComplete -> _infoComplete', _infoComplete);
      return _infoComplete;
    },
    clickGoback () {
      this.$router.go(-1);
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 根据所在地区Code找到对应name
    addressDataForCheck (_provinceCode, _cityCode, _countyCode) {
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      return `${_provinceData ? _provinceData.name : ''} ${_cityData ? _cityData.name : ''} ${_countyData ? _countyData.name : ''}`;
    },
    errorPhoto() {
      const img = event.srcElement;
      img.src = this.defaultPhoto;
      img.onerror = null;
    }
  }
};
</script>

<style lang="scss" scoped>
.confirmInfo_list_wrap {
  // min-height: 444px;
  margin-bottom: 20px;
}
.confirmInfo_list {
  display: flex;
  flex-wrap: wrap;
}
.confirmInfo_item {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 160px;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0px 0px 10px 0px rgba(0,0,0,0.10);
}
.confirmInfo_item_filling {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  padding: 0 20px;
  border-radius: 8px;
}
.confirmInfo_img_wrap {
  box-sizing: content-box;
  position: relative;
  width: 108px;
  height: 108px;
  padding-top: 24px;
  overflow: hidden;
}
.confirmInfo_img {
  width: 108px;
  height: 108px;
  border-radius: 50%;
  object-fit: cover;
}
.confirmInfo_info {
  padding-top: 24px;
  margin-left: 132px;
}
.confirmInfo_info_title {
  padding-bottom: 12px;
  margin-bottom: 8px;
  line-height: 28px;
  color: #353434;
  font-weight: bold;
  border-bottom: 1px dashed #979797;
}
.confirmInfo_info_desc,
.confirmInfo_info_type {
  width: 100%;
  padding-bottom: 4px;
  font-size: 14px;
  line-height: 20px;
}
.confirmInfo_item_edit {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 40px;
  color: #666666;
  background: #ffffff;
  font-size: 12px;
  border-radius: 5px;
  box-shadow: 0 0 5px 0 rgba(0,0,0,0.10);
}
.noConfirmInfo {
  width: 100%;
  text-align: center;
  padding: 50px 0;
  text-align: center;
  color: #aaa;
}

.popup_btns {
  padding: 20px 10px;
}

.add_member .add_member_content {
  position: absolute;
  top: 46px;
  bottom: 0;
  width: 100%;
  left: 0;
  overflow: auto;
}

.no_info_gray {
  color: #979797;
}
</style>
